<template>
	<view>
		<view class="image-box" @click="cimage">
			<image class="image" :src="imageUrl" mode="aspectFill"></image>
			<view class="image-fc" v-if="!imageUrl">
				点击选择图片
			</view>
		</view>
		<view class="input-box">
			<view>图片标题：</view>
			<input type="text" v-model="title" />
		</view>
		<view class="input-box">
			<view>上下边距：</view>
			<input type="number" v-model="input.s" />
			rpx
		</view>
		<view class="input-box">
			<view>左右边距：</view>
			<input type="number" v-model="input.x" />
			rpx
		</view>
		<button class="button" type="default" @click="upload">开始上传</button>
	</view>
</template>

<script>
	const db = uniCloud.database();

	export default {
		data() {
			return {
				title: "",
				imageUrl: "",
				fileName: "",
				input: {
					s: 0,
					x: 0
				}
			}
		},
		methods: {
			cimage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const timestamp = (new Date()).valueOf();
						let fileName = res.tempFiles[0].name.split('.')
						this.fileName = timestamp + '.' + fileName[fileName.length - 1]
						this.imageUrl = res.tempFilePaths[0]
					}
				})
			},
			upload() {
				uni.showLoading({
					title:'上传中…',
				})
				const bannerfile = this.imageUrl
				const ps = this.input
				const position = `${ps.s}rpx ${ps.x}rpx`
				if (!bannerfile) return uni.showToast({
					title: "请选择一张图片",
					icon: "none"
				})
				if (!this.title) return uni.showToast({
					title: "请选填写标题",
					icon: "none"
				})
				uniCloud.uploadFile({
					filePath: bannerfile,
					cloudPath: this.fileName,
					success: (res) => {
						db.collection('opendb-banner').add({
							position,
							title: this.title,
							bannerfile: res.fileID,
						}).then(res=>{
							uni.hideLoading()
							uni.showToast({
								title:'添加成功',
								icon:'none'
							})
							this.imageUrl = ''
							this.fileName = ''
							this.input = {
								s:0,
								x:0
							},
							this.title = ''
						})
					}
				});
			}
		}
	}
</script>
<style>
	.image-box {
		margin: 20rpx 30rpx;
		width: 690rpx;
		height: 820rpx;
		background-color: #eee;
		border-radius: 10rpx;
	}

	.image {
		width: 100%;
		height: 100%;
		border: 1px dashed #999999;
		border-radius: 10rpx;
	}

	.image-fc {
		margin: 20rpx 30rpx;
		position: absolute;
		width: 300rpx;
		height: 200rpx;
		line-height: 200rpx;
		left: 225rpx;
		top: 300rpx;
		text-align: center;
	}

	.input-box {
		margin: 20rpx 30rpx;
		display: flex;
		align-items: center;
	}

	.input-box input {
		padding: 4rpx 10rpx;
		border-bottom: 1px solid #999999;
	}

	.button {
		margin: 30rpx;
	}
</style>
